<template>
  <div class="box">
    <div class="top">
      <div class="help">
          帮助
      </div>
    </div>
    <div class="content">
      <h1>邮箱登录</h1>
      <p>未注册的邮箱号登录后自动注册</p>
      <div class="phone">
        <span>Email</span>
        <span>
          <svgIcon iconName="icon-xialakuang"></svgIcon>
        </span>
        <input type="text" placeholder="请输入邮箱号" v-model="email" @input="validateEmail">
      </div>
      <div class="yzm" v-show="showYzm">
        <input type="text" placeholder="输入验证码" v-model="verificationCode" maxlength="6">
        <span v-if="countdown > 0">重新发送({{ countdown }}s)</span>
        <span v-else @click="sendVerificationCode" style="cursor: pointer; color: #001546;">重新发送</span>
      </div>
      <div class="qtwt">
        <div class="qh">
          <svgIcon icon-name="icon-zhihuan"></svgIcon>
          密码登录
        </div>
        <div class="sjh">
          邮箱无法使用
        </div>
      </div>
      <div class="login" :class="{ 'valid': isValidEmail, 'active': isValidEmail }" @click="handleLogin">
        {{ showYzm ? '验证并登录' : '发送验证码' }}
      </div>
      <div class="sq">
        <input type="radio" class="custom-radio">
        我已阅读并同意
        <span>《用户协议》</span>
        <span>《隐私政策》</span>
        <span>《未成年人个人信息保护规则》</span>
      </div>
      <div class="gd">
        <div><svgIcon iconName="icon-QQ" font-size="60px"></svgIcon></div>
        <div><svgIcon iconName="icon-pinpaibiaoshi_wangyiyouxiang" font-size="60px"></svgIcon></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import svgIcon from '@/components/svgIcon.vue';
import router from '@/router';
import { ref, computed, onUnmounted } from 'vue';
import websocketService from '@/services/websocket';

const email = ref('');
const verificationCode = ref('');
const showYzm = ref(false);
const countdown = ref(0);
const isSending = ref(false);
const isVerifying = ref(false);
let countdownTimer = null;

// 邮箱格式验证正则表达式
const emailRegex = /^[^\s@]+@(qq\.com|163\.com)$/;

const isValidEmail = computed(() => {
  return emailRegex.test(email.value);
});

const validateEmail = () => {
  // 邮箱格式验证，但不自动显示验证码输入框
  // 验证码输入框只在发送验证码成功后显示
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!isValidEmail.value || isSending.value || countdown.value > 0) {
    return;
  }

  isSending.value = true;
  
  try {
    const response = await fetch('http://1.14.98.17:7543/api/auth/send-verification', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email.value
      })
    });

    const data = await response.json();
    
    if (response.ok) {
      // 发送成功，显示验证码输入框并开始倒计时
      showYzm.value = true;
      countdown.value = 300; // 300秒
      startCountdown();
      alert('验证码已发送到您的邮箱');
    } else {
      alert(data.message || '发送验证码失败');
    }
  } catch (error) {
    console.error('发送验证码错误:', error);
    alert('网络错误，请重试');
  } finally {
    isSending.value = false;
  }
};

// 倒计时功能
const startCountdown = () => {
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(countdownTimer);
    }
  }, 1000);
};

// 验证验证码
const verifyCode = async () => {
  if (!verificationCode.value || verificationCode.value.length !== 6) {
    alert('请输入6位验证码');
    return;
  }

  isVerifying.value = true;
  
  try {
    const response = await fetch('http://1.14.98.17:7543/api/auth/verify-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email.value,
        code: verificationCode.value
      })
    });

    const data = await response.json();
    
    if (response.ok) {
      // 验证成功，检查用户是否存在
      await checkAndCreateUser();
    } else {
      alert(data.message || '验证码错误');
    }
  } catch (error) {
    console.error('验证验证码错误:', error);
    alert('网络错误，请重试');
  } finally {
    isVerifying.value = false;
  }
};

// 检查用户是否存在，不存在则创建
const checkAndCreateUser = async () => {
  try {
    // 先查询用户是否存在
    const checkResponse = await fetch(`http://1.14.98.17:8765/api/accounts/email/${encodeURIComponent(email.value)}`);
    
    let userId = null;
    
    if (checkResponse.ok) {
      const userData = await checkResponse.json();
      if (userData.success && userData.data && userData.data.user_id) {
        // 用户已存在，获取user_id
        userId = userData.data.user_id;
      }
    }
    
    // 如果用户不存在，创建新用户
    if (!userId) {
      const createResponse = await fetch('http://1.14.98.17:8765/api/accounts/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: email.value,
          password: '123456'
        })
      });

      const createData = await createResponse.json();
      
      if (createResponse.ok && createData.success) {
        // 创建成功，获取user_id
        userId = createData.data.user_id;
      } else {
        alert(createData.message || '创建用户失败');
        return;
      }
    }
    
    // 通过user_id查询获取单个用户信息
    const userInfoResponse = await fetch(`http://1.14.98.17:8765/api/users/${userId}`);
    
    if (userInfoResponse.ok) {
      const userInfoData = await userInfoResponse.json();
      if (userInfoData.success) {
        // 用户信息存在，保存user_id
        localStorage.setItem('user_id', userId);
        // 初始化 WebSocket 连接
        websocketService.init(userId);
        alert('登录成功');
        router.push('/home');
      } else {
        // 用户信息不存在，创建用户信息
        await createUserInfo(userId);
      }
    } else if (userInfoResponse.status === 404) {
      // 404错误说明用户信息不存在，创建用户信息
      await createUserInfo(userId);
    } else {
      alert('查询用户信息失败');
    }
  } catch (error) {
    console.error('检查/创建用户错误:', error);
    alert('网络错误，请重试');
  }
};

// 创建用户信息
const createUserInfo = async (userId) => {
  try {
    const createUserInfoResponse = await fetch('http://1.14.98.17:8765/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_id: userId,
        nickname: '未设置名称',
        avatar_url: ''
      })
    });

    const createUserInfoData = await createUserInfoResponse.json();
    
    if (createUserInfoResponse.ok && createUserInfoData.success) {
      // 创建用户信息成功，保存user_id
      localStorage.setItem('user_id', userId);
      // 初始化 WebSocket 连接
      websocketService.init(userId);
      alert('登录成功');
      router.push('/home');
    } else {
      alert(createUserInfoData.message || '创建用户信息失败');
    }
  } catch (error) {
    console.error('创建用户信息错误:', error);
    alert('网络错误，请重试');
  }
};

// 处理登录按钮点击
const handleLogin = () => {
  if (!isValidEmail.value) {
    alert('请输入正确的邮箱格式');
    return;
  }

  if (showYzm.value) {
    // 验证并登录
    verifyCode();
  } else {
    // 直接发送验证码
    sendVerificationCode();
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="less" scoped>
  .box {
    width: 100%;
    height: 100vh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    .top {
      width: 100%;
      height: 100px;
      display: flex;
      justify-content: end;
      .help {
        width: 200px;
        text-align: center;
        line-height: 100px;
        font-size: 32px;
        color: #989898;
      }
    }
    .content {
      width: 100%;
      padding: 0 90px;
      text-align: center;
      h1 {
        margin-top: 20px;
      }
      p {
        color: #989898;
        margin-top: 20px;
      }
      .phone {
        margin-top: 100px;
        height: 70px;
        width: 570px;
        display: flex;
        border-bottom: 1px solid gray;
        span {
          font-size: 40px;
          margin-right: 20px;
        }
        input {
          width: 400px;
          height: 60px;
          font-size: 32px;
        }
      }
      .yzm {
        margin-top: 20px;
        width: 570px;
        height: 70px;
        border-bottom: 1px solid gray;
        display: flex;
        justify-content: space-between;
        align-items: center;
        input {
          width: 300px;
          height: 60px;
          font-size: 32px;
        }
        span {
          font-size: 28px;
          color: #989898;
        }
      }
      .qtwt {
        margin-top: 20px;
        width: 570px;
        height: 60px;
        color: #001546;
        font-size: 28px;
        display: flex;
        justify-content: space-between;
      }
      .login {
        width: 570px;
        height: 80px;
        border-radius: 40px;
        background-color: #f5f5f5;
        color: #fff;
        font-size: 40px;
        line-height: 80px;
        text-align: center;
        margin-top: 20px;
        cursor: pointer;
        
        &.valid {
          background-color: #001546;
        }
        
        &.active {
          background-color: #4CAF50;
        }
      }
      .sq {
        width: 570px;
        height: 80px;
        font-size: 28px;
        margin-top: 50px;
        .custom-radio {
          width: 22px;
          height: 22px;
          margin-right: 10px;
          cursor: pointer;
          -webkit-appearance: none;
          -moz-appearance: none;
          appearance: none;
          border: 2px solid #001546;
          border-radius: 50%;
          outline: none;
          position: relative;
          &:checked {
            background-color: #001546;
            &::after {
              content: '';
              position: absolute;
              width: 16px;
              height: 16px;
              background-color: #001546;
              border-radius: 50%;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
        }
        span {
          color: #001546;
          margin: 0 5px;
        }
      }
      .gd {
        margin-top: 130px;
        width: 570px;
        height: 80px;
        display: flex;
        justify-content: space-around;
        div {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          border: 1px solid gray;
          padding:10px 0 ;
        }
      }
    }
  }
</style>
